package com.fmx.BookStore.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.fmx.BookStore.core.domain.AjaxResult;
import com.fmx.BookStore.domain.Permission;
import com.fmx.BookStore.domain.Role;
import com.fmx.BookStore.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    IRoleService roleService;

    @GetMapping(value = "/{roleId}")
    @ApiOperation("根据ID找角色")
    public AjaxResult selectRoleById(@PathVariable("roleId") Long roleId){
        return AjaxResult.success(roleService.selectRoleById(roleId));
    }
    @GetMapping("/list")
    @ApiOperation("根据其他信息查询角色")
    public AjaxResult listRole(Role role){
        List<Role> list = roleService.listRole(role);
        return AjaxResult.success(list);
    }

    @PostMapping
    @ApiOperation("新增角色")
    public AjaxResult addRole(@RequestBody Role role){
        int rows = roleService.insertRole(role);
        return rows > 0 ? AjaxResult.success("添加角色成功") : AjaxResult.error("添加角色失败");
    }

    @PutMapping
    @ApiOperation("修改角色信息")
    public AjaxResult updateRole(@RequestBody Role role){
        int rows = roleService.updateRole(role);
        return rows > 0 ? AjaxResult.success("修改角色成功") : AjaxResult.error("修改角色失败");
    }

    @DeleteMapping("/{roleId}")
    @ApiOperation("删除角色")
    public AjaxResult deleteRole(@PathVariable Long roleId){
        int rows = roleService.deleteRole(roleId);
        return rows > 0 ? AjaxResult.success("删除角色成功") : AjaxResult.error("删除角色失败");
    }

    @GetMapping("/page")
    @ApiOperation("分页操作")
    public AjaxResult page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize, Role role){
        PageHelper.startPage(pageNum,pageSize);
        List<Role> list = roleService.listRole(role);
        PageInfo<List> pageInfo = new PageInfo(list);
        return AjaxResult.success(pageInfo);
    }

    /**
     * 绑定角色和菜单的关系
     * @param roleId 角色id
     * @param permissionId 菜单id数组
     * @return
     */
    @PostMapping("/rolePermission/{roleId}")
    public AjaxResult rolePermission(@PathVariable Long roleId, @RequestBody List<Long> permissionId) {
        roleService.setRolePermission(roleId, permissionId);
        return AjaxResult.success();
    }

    @GetMapping("/rolePermission/{roleId}")
    public AjaxResult getRolePermission(@PathVariable Long roleId) {
        return AjaxResult.success( roleService.getRolePermission(roleId));
    }

}
